﻿CREATE PROCEDURE [audit].[LoadTraceData]
@TraceName NVARCHAR (255), @TracePath NVARCHAR (512)
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int
	SET @RC = 0

	DECLARE @Columns nvarchar(512)
	EXEC @RC = audit.GetTraceColumns @TraceName, @Columns OUTPUT
	IF(@@ERROR <> 0)
	OR(@RC <> 0)
		RETURN(@RC)

	PRINT 'Loading trace data...'

	DECLARE @Statement nvarchar(1024)
	SET @Statement = N'SELECT ''' 
		+ @TraceName 
		+ N''' AS [TraceName], ' 
		+ @Columns 
		+ N', CONVERT(char(8),GETDATE(),112) AS [LoadDate]'
		+ N' INTO #TRACEDATA'
		+ N' FROM :: fn_trace_gettable('''
		+ @TracePath
		+ N'.trc'', default)'
		+ N' INSERT audit.TraceData ([TraceName], '
		+ @Columns
		+ N', [LoadDate]) '
		+ N'SELECT * FROM #TRACEDATA'

	EXEC @RC = dbo.sp_executesql @statement

	PRINT N'('
		+ CAST(@@ROWCOUNT AS nvarchar)
		+ N' row(s) loaded)'

	RETURN(@RC)
END